package com.miaosha.redis.hash;

import redis.clients.jedis.Jedis;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author lsq
 * @create 2021-10-10 10:14
 * @description 令牌回话机制
 * @menu
 **/
public class Token {

    private Jedis jedis = new Jedis("182.42.113.98", 6379);

    public boolean isSessionValid(String token) throws ParseException {

        if (token == null || "".equals(token)) {
            return false;
        }

        // json字符串
        String session = jedis.hget("session", "session::" + token);

        if (session == null || "".equals(session)) {
            return false;
        }

        // 检查一下session是否在有效期
        String expireTime = jedis.hget("session::expire_time", "session::" + token);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date expireDate = simpleDateFormat.parse(expireTime);

        Date now = new Date();

        if (now.after(expireDate)) {
            return false;
        }

        return true;
    }

    /**
     * 初始化session
     *
     * @param userId
     * @param token
     */
    public void login(long userId, String token) {

        // 1、session
        jedis.hset("session", "session::" + token, String.valueOf(userId));

        // 2、过期时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.HOUR, 24);
        Date expireTime = calendar.getTime();

        jedis.hset("session::expire_time", "session::" + token, simpleDateFormat.format(expireTime));
    }

}
